<script lang="ts" setup>
import auth from '@/api/auth'
import mcht from '@/api/mcht'
import { useAuthStore } from '@/store'
import { cleanStringCompact } from '@/utils/shared.ts'

const { sessionid } = storeToRefs(useAuthStore())

const form = ref({
  phone: '',
  code: '',
  id: '',
  type: '',
  password: '',
  confirmPassword: '',
})

const merchantSelectRef = ref()

watch(() => form.value.phone, async (value) => {
  if (value.length >= 11) {
    merchantSelectRef.value.getList(value)
  }
})

const second = ref(0)
const interval = ref()
async function getCode() {
  if (form.value.phone === '') {
    uni.showToast({
      icon: 'none',
      title: '请先输入手机号',
    })
  }
  else if (form.value.id === '') {
    uni.showToast({
      icon: 'none',
      title: '请选择商户/门店',
    })
  }
  else {
    const { data } = await auth.getDynamicCode({
      phoneNumber: form.value.phone,
      merchantId: form.value.id
    })
    if (data.status === 'success') {
      second.value = 60
      interval.value = setInterval(() => {
        second.value = second.value - 1
        if (second.value <= 0) {
          second.value = 0
          clearInterval(interval.value)
        }
      }, 1000)
    }
  }
}
const loading = ref<boolean>(false)
async function confirm() {
  if (form.value.phone === '') {
    uni.showToast({
      icon: 'none',
      title: '请先输入手机号',
    })
  }
  else if (form.value.id === '') {
    uni.showToast({
      icon: 'none',
      title: '请选择商户/门店',
    })
  }
  else if (form.value.code === '') {
    uni.showToast({
      icon: 'none',
      title: '请输入验证码',
    })
  }
  else if (form.value.password === '' || form.value.password.length < 9) {
    uni.showToast({
      icon: 'none',
      title: '请输入新密码,且密码需大于等于9位',
    })
  }
  else if (form.value.password !== form.value.confirmPassword) {
    uni.showToast({
      icon: 'none',
      title: '确认密码与新密码不一致',
    })
  }
  else {
    loading.value = true
    let postData = {
      phoneNumber: form.value.phone,
      password: form.value.password,
      verificationCode: form.value.code,
    }
    if (form.value.type === 'M') {
      postData = Object.assign(postData, {
        mchtNo: form.value.id,
      })
    }
    if (form.value.type === 'S') {
      postData = Object.assign(postData, {
        storeId: form.value.id,
      })
    }
    const { data } = await mcht.loginAndQuery(postData)
    loading.value = false
    if (data.status === 'success') {
      sessionid.value = data?.data.sessionid
      // token.value = data?.data.token
      if (data?.data.needReset) {
        uni.navigateTo({
          url: `/pages/login/reset?phone=${form.value.phone}`,
        })
      }
    }
    else {
      // 重置验证码和密码
      form.value.code = ''
      form.value.password = ''
      form.value.confirmPassword = ''
    }
  }
}
function cancel() {
  uni.navigateBack()
}

const passwordType = ref('password')
function handlePassword() {
  passwordType.value === 'password'
    ? (passwordType.value = 'text')
    : (passwordType.value = 'password')
}

// 处理输入事件
function handleInputPassword(inputName, event) {
  const value = event
  const filteredValue = cleanStringCompact(value)
  form.value[inputName] = filteredValue
}
</script>

<template>
  <div class="first">
    <div class="top">
      <div class="title">首次登录</div>
      <div class="desc">请输入手机号商和户/门店号</div>
      <nut-divider :custom-style="{ color: '#e8e8e8' }" />
      <div class="form">
        <nut-form :model-value="form">
          <nut-form-item label="手机号" label-align="center">
            <nut-input v-model="form.phone" placeholder="请输入手机号" />
          </nut-form-item>
          <nut-form-item label="商户/门店" label-align="center">
            <login-merchant-select ref="merchantSelectRef" v-model="form.id"
              v-model:type="form.type"></login-merchant-select>
          </nut-form-item>
          <nut-form-item label="验证码" label-align="center">
            <nut-input v-model="form.code" placeholder="请输入验证码">
              <template #right>
                <nut-button v-if="second === 0" type="primary" size="small" @click="getCode">获取验证码</nut-button>
                <nut-button v-else type="primary" size="small" disabled>{{ second }}</nut-button>
              </template>
            </nut-input>
          </nut-form-item>
          <nut-form-item label="新密码" label-align="center">
            <!-- <nut-input v-model="form.password" type="password" placeholder="请输入新密码" /> -->

            <nut-input v-if="passwordType === 'password'" v-model="form.password" placeholder="请输入新密码"
              :type="passwordType" @input="handleInputPassword('password', $event)">
              <template #right>
                <div class="show-password" @click="handlePassword">
                  <div class="i-ri:eye-off-fill"></div>
                </div>
              </template>
            </nut-input>

            <nut-input v-else v-model="form.password" placeholder="请输入新密码" :type="passwordType"
              @input="handleInputPassword('password', $event)">
              <template #right>
                <div class="show-password" @click="handlePassword">
                  <div class="i-ri:eye-fill"></div>
                </div>
              </template>
            </nut-input>

          </nut-form-item>
          <nut-form-item label="确认密码" label-align="center">
            <!-- <nut-input v-model="form.confirmPassword" type="password" placeholder="请再次输入密码" /> -->
            <nut-input v-if="passwordType === 'password'" v-model="form.confirmPassword" placeholder="请再次输入密码"
              :type="passwordType" @input="handleInputPassword('confirmPassword', $event)">
              <template #right>
                <div class="show-password" @click="handlePassword">
                  <div class="i-ri:eye-off-fill"></div>
                </div>
              </template>
            </nut-input>

            <nut-input v-else v-model="form.confirmPassword" placeholder="请再次输入密码" :type="passwordType"
              @input="handleInputPassword('confirmPassword', $event)">
              <template #right>
                <div class="show-password" @click="handlePassword">
                  <div class="i-ri:eye-fill"></div>
                </div>
              </template>
            </nut-input>
          </nut-form-item>
        </nut-form>
      </div>
    </div>
    <div class="button">
      <nut-button type="primary" :loading="loading" block @click="confirm">确定</nut-button>
    </div>
    <div class="button" style="margin-top: 0">
      <nut-button type="danger" block style="margin-top: 10px" @click="cancel">取消</nut-button>
    </div>
  </div>
</template>

<route lang="json">
  {
    "style": {
      "navigationBarTitleText": "商户登录",
      "backgroundColorContent": "#ffffff"
    }
  }
  </route>

  <style lang="sass" scoped>
  .first
    .top
      background-color: #fff
      text-align: center
      padding: 30px
      .title
        font-weight: bold
        font-size: 20px
        margin-bottom: 10px
      .desc
        color: #8e8e8e
        margin-bottom: 40px
      .form
        margin-top: 40px
        .space
          display: flex
          justify-content: space-around
          padding: 10px
    .button
      margin: 10px 20px
  </style>
